package com.tiger.userClient.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;

@Aspect
@Component
public class AuthAspect {


    @Around("@annotation(requireAuth)")
    public Object checkAuth(ProceedingJoinPoint joinPoint, RequireAuth requireAuth) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        Boolean isAuth = (Boolean) request.getAttribute("isAuth");

        System.out.println("---------------------");
        System.out.println(isAuth);

        if (isAuth == null || !isAuth) {
            if (response != null) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized access");
                return null; // 不继续执行目标方法
            }
        }
        return joinPoint.proceed(); // 继续执行目标方法
    }
}
